﻿using Aurora.AI.Abstractions;
using Aurora.AI.Abstractions.Dtos;
using Aurora.AI.Abstractions.Embeddings;
using Aurora.AI.Abstractions.ObjectModels.RequestModels;
using Aurora.AI.Abstractions.ObjectModels.ResponseModels;
using Sdcb.DashScope;
using Sdcb.DashScope.TextEmbedding;

namespace Aurora.AI.Qiansail.Embeddings;

public class QiansailTextEmbeddingService : IAuroraAITextEmbeddingService
{
    public async Task<EmbeddingCreateResponse> EmbeddingAsync(EmbeddingCreateRequest createEmbeddingModel,
        AuroraAIPlatformOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        using DashScopeClient client = new(options!.ApiKey!);
        // 最大的批次是 一次 25条
        int count= createEmbeddingModel.InputCalculated.Count;

        EmbeddingCreateResponse response = new()
        {
            Model = createEmbeddingModel.Model,
            Usage = new AuroraAIUsageResponse()
            {
            }
        };
        // 如果大于25条 则进行 分批处理
        if (count > 25)
        {
            bool next = true;
            int page = 1;
            int size = 25;
            while (next)
            {
                var data= createEmbeddingModel.InputCalculated.Skip((page - 1) * size).Take(size).ToList();
                if (data.Count > 0)
                {
                    await SendAsync(client, createEmbeddingModel.Model, data, response);
                }
                else
                {
                    next = false;
                }

                page++;
            }
        }
        else
        {
            await SendAsync(client, createEmbeddingModel.Model, createEmbeddingModel.InputCalculated.ToList(), response);
        }
        return response;
    }


    private async Task SendAsync(DashScopeClient client,string model,List<string> data,EmbeddingCreateResponse response)
    {
        var result = await client.TextEmbedding.GetEmbeddings(new EmbeddingRequest
        {
            Model = model,
            InputTexts = data,
        });
        if (response.Data == null)
        {
            response.Data = new List<EmbeddingResponse>();
        }
        response.Data.AddRange(result.Output.Embeddings.Select(x => new EmbeddingResponse()
        {
            Embedding = x.Embedding.ToList(),
            Index = x.TextIndex
        }).ToList());
    }
}